package com.mujin.keji.collectionsystem.utils.ImageLoader.glide;

import android.graphics.drawable.Drawable;
import android.os.Process;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;


import com.bumptech.glide.DrawableTypeRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.mujin.keji.collectionsystem.utils.ImageLoader.base.BaseLoaderConfig;
import com.mujin.keji.collectionsystem.utils.ImageLoader.base.ILoader;


/**
 * @author 作者：weishixiong
 * @date 创建时间：2018/5/2
 * @corporation 公司：mujin
 * @desception Glide加载图片
 */

public class GliderLoader implements ILoader {
    
    private GlideConfig mConfig;
    private DrawableTypeRequest request;
    
    @Override
    public void init() {
        RequestManager manager = Glide.with(mConfig.getContext());
        request = getDrawableTypeRequest(mConfig, manager);
        if (request == null) {
            throw new IllegalArgumentException("no image load path had be set");
        }
        if (mConfig.getStrategy() != null) {
            request.diskCacheStrategy(mConfig.getStrategy());
        } else {
            request.diskCacheStrategy(DiskCacheStrategy.SOURCE);
        }
        
        GlideBuilder builder = new GlideBuilder(mConfig.getContext());
        if (mConfig.getCacheSize() > 0) {
            builder.setDiskCache(new ExternalCacheDiskCacheFactory(mConfig.getContext(), mConfig.getCacheSize() * 1024 * 1024));
        }
        
        if (mConfig.getErrorImg() > 0) {
            request.error(mConfig.getErrorImg());
        }
        
        if (mConfig.getPlaceHolder() > 0) {
            request.placeholder(mConfig.getPlaceHolder());
        }
        
        if (mConfig.getImgHeight() > 0 && mConfig.getImgWidth() > 0) {
            request.override(mConfig.getImgWidth(), mConfig.getImgHeight());
        }
        
        if (mConfig.getAnimator() != null) {
            request.animate(mConfig.getAnimator());
        } else {
            request.dontAnimate();
        }
        
        if (mConfig.getTransformation() != null) {
            request.bitmapTransform(mConfig.getTransformation());
        }
        
        if (mConfig.getListener() != null) {
            request.listener(new RequestListener<Object, Drawable>() {
                @Override
                public boolean onException(Exception e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    mConfig.getListener().onLoadFailure(e);
                    return false;
                }
                
                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                    Log.d("GliderLoader","resource:" + resource.toString()
                            + "----model:" + model + "----isFromMemoryCache:" + isFromMemoryCache + "----isFirstResource:" + isFirstResource);
                    mConfig.getListener().onLoadSuccess(resource);
                    return false;
                }
            });
        }
    }
    
    @Nullable
    private DrawableTypeRequest getDrawableTypeRequest(GlideConfig config, RequestManager requestManager) {
        DrawableTypeRequest request = null;
        if (!TextUtils.isEmpty(config.getImagePath())) {
            request = requestManager.load(config.getImagePath());
        } else if (config.getUri() != null) {
            request = requestManager.load(config.getUri());
        } else if (config.getFile() != null) {
            request = requestManager.load(config.getFile());
        } else if (config.getResId() > 0) {
            request = requestManager.load(config.getResId());
        } else if (config.getImgBytes() != null && config.getImgBytes().length > 0) {
            request = requestManager.load(config.getImgBytes());
        }
        return request;
    }
    
    @Override
    public void loadImage() {
        assetConfig();
        
        if (mConfig.getImageView() == null) {
            throw new IllegalArgumentException("imageView can not be null");
        }
        request.into(mConfig.getImageView());
    }
    
    @Override
    public void clearMemCache() {
        assetConfig();
        
        Glide.get(mConfig.getContext()).clearMemory();
    }
    
    @Override
    public void clearSdCache() {
        assetConfig();
        
        new Thread(new Runnable() {
            @Override
            public void run() {
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                Glide.get(mConfig.getContext()).clearDiskCache();
            }
        }).start();
    }
    
    @Override
    public void clearAllCache() {
        clearMemCache();
        clearSdCache();
    }
    
    @Override
    public GlideConfig getConfig() {
        assetConfig();
        return mConfig;
    }
    
    @Override
    public void setConfig(BaseLoaderConfig config) {
        if (config == null || !(config instanceof GlideConfig)) {
            throw new IllegalArgumentException("Config and Loader must be conforming");
        }
        
        mConfig = (GlideConfig) config;
    }
    
    private void assetConfig() {
        if (mConfig == null) {
            throw new IllegalArgumentException("config must not be null");
        }
    }
}
